/*******************************************************************************
 * Copyright 2011 WaTho
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.wathoserver.android.dragoid.activity;

import java.util.Map.Entry;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import de.wathoserver.android.dragoid.R;
import de.wathoserver.android.dragoid.activity.tabs.OverviewActivity;
import de.wathoserver.android.dragoid.activity.util.AccountActivity;
import de.wathoserver.android.dragoid.activity.util.PrefsActivity;
import de.wathoserver.android.dragoid.activity.util.ShowLogActivity;
import de.wathoserver.android.dragoid.api.DragoApi;
import de.wathoserver.android.dragoid.api.DragoidConstants;
import de.wathoserver.android.dragoid.util.LogCollector;

/**
 * Einstiegspunkt in die Anwendung. Kümmert sich um die Initialisierung der
 * Benutzereinstellungen und zeigt das Hauptmenü an.
 * 
 * @author watho
 * 
 */
public class MainActivity extends Activity implements DragoidConstants {

	public static final int DIALOG_SEND_LOG = 345350;
	protected static final int DIALOG_PROGRESS_COLLECTING_LOG = 3255;
	protected static final int DIALOG_FAILED_TO_COLLECT_LOGS = 3535122;
	private static final int DIALOG_REPORT_FORCE_CLOSE = 3535788;

	LogCollector logCollector;
	private Button buildingsBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		logCollector = new LogCollector(this);
		CheckForceCloseTask task = new CheckForceCloseTask();
		task.execute();
		setContentView(R.layout.main);
		buildingsBtn = (Button) findViewById(R.id.main_buildings);
	}

	@Override
	protected void onResume() {
		super.onResume();
		try {
			DragoApi.initDragoApi(this);
			buildingsBtn.setEnabled(true);
		} catch (Exception e) {
			Log.e(LOG_TAG, "Init dragoapi failed", e);
			buildingsBtn.setEnabled(false);
			AlertDialog.Builder b = new AlertDialog.Builder(this);
			AlertDialog d = b
					.setCancelable(true)
					.setMessage(
							"Fehler in den Kontoeinstellungen: "
									+ e.getMessage()
									+ "\n"
									+ DragoApi.getLastError()
									+ "\nBitte gehe in die Kontoeinstellungen und überprüfe den Permanentlink")
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setPositiveButton("OK", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).create();
			d.show();
		}
	}

	/**
	 * Gibt alle benutzerdefinierten Einstellungen auf der Konsole aus,
	 */
	private void logPrefs() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		for (Entry<String, ?> entry : prefs.getAll().entrySet()) {
			Log.d(LOG_TAG,
					String.format("%s=%s", entry.getKey(), entry.getValue()));
		}
	}

	/**
	 * Öffnet dein Accounteinstellungsdialog
	 */
	public void openAccountSettings() {
		Intent intent = new Intent().setClass(this, AccountActivity.class);
		intent.putExtra("automatic", true);
		startActivity(intent);
	}

	private void startOverviewActivity() {
		DragoApi.initDragoApi(this);
		Intent intent = new Intent(this, OverviewActivity.class);
		startActivity(intent);
	}

	/**
	 * Wird von Button in xml aufgerufen. Zeigt Gebäude- und Warentabs an.
	 * 
	 * @param v
	 */
	public void showOverview(View v) {
		startOverviewActivity();
	}

	/**
	 * Wird von Button in xml aufgerufen. Zeigt den Markt an.
	 * 
	 * @param v
	 */
	public void showMarket(View v) {
		// startOverviewActivity();
		Toast.makeText(this, "Noch nicht implementiert", Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * Wird von Button in xml aufgerufen. Zeigt die Drachenzucht an.
	 * 
	 * @param v
	 */
	public void showDragon(View v) {
		// startOverviewActivity();
		Toast.makeText(this, "Noch nicht implementiert", Toast.LENGTH_SHORT)
				.show();
	}

	/**
	 * Wird von Button in xml aufgerufen.
	 * 
	 * @param v
	 */
	public void sendLog(View v) {
		showDialog(DIALOG_SEND_LOG);
	}

	/**
	 * Wird von Button in xml aufgerufen.
	 * 
	 * @param v
	 */
	public void showLog(View v) {
		new AsyncTask<Void, Void, Boolean>() {
			@Override
			protected Boolean doInBackground(Void... params) {
				logPrefs();
				return logCollector.collect();
			}

			@Override
			protected void onPreExecute() {
				showDialog(DIALOG_PROGRESS_COLLECTING_LOG);
			}

			@Override
			protected void onPostExecute(Boolean result) {
				dismissDialog(DIALOG_PROGRESS_COLLECTING_LOG);
				if (result) {
					Intent intent = new Intent(MainActivity.this,
							ShowLogActivity.class);
					intent.putExtra("log", logCollector.getLastLogs());
					startActivity(intent);
				} else {
					showDialog(DIALOG_FAILED_TO_COLLECT_LOGS);
				}
			}
		}.execute();
	}

	/**
	 * Wird von Button in xml aufgerufen.
	 * 
	 * @param v
	 */
	public void openAccountSettings(View v) {
		Intent intent = new Intent().setClass(this, AccountActivity.class);
		startActivityForResult(intent, 0);
	}

	/**
	 * Wird von Button in xml aufgerufen.
	 * 
	 * @param v
	 */
	public void openHelp(View v) {
		Uri uri = Uri
				.parse("http://code.google.com/p/dragoid/wiki/FunktionsBeschreibung");
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
	}

	/**
	 * Wird von Button in xml aufgerufen.
	 * 
	 * @param v
	 */
	public void openPrefs(View v) {
		Intent intent = new Intent().setClass(this, PrefsActivity.class);
		startActivityForResult(intent, 0);
	}

	/**
	 * Wird von Button in xml aufgerufen.
	 * 
	 * @param v
	 */
	public void openDragosien(View v) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		String permanentLogin = prefs
				.getString("account_permanent_login", null);
		Uri uri = null;
		if (permanentLogin != null
				&& DragoApi.isValidPermanentLogin(permanentLogin) == null) {
			uri = Uri.parse(permanentLogin);
		} else {
			uri = Uri.parse("http://www.dragosien.de");
		}
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent);
	}

	/**
	 * Wird von Button in xml aufgerufen.
	 * 
	 * @param v
	 */
	public void closeDragoid(View v) {
		// TODO Test, ob das ausreicht
		this.finish();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case DIALOG_SEND_LOG:
		case DIALOG_REPORT_FORCE_CLOSE:
			Builder builder = new AlertDialog.Builder(this);
			String message;
			if (id == DIALOG_SEND_LOG)
				message = "Willst du dem Enwickler die Logdatei schicken?";
			else
				message = "Es scheint als ob die Anwendung wegen eines Fehlers geschlossen wurde. Willst du dem Entwickler die Logdatei schicken?";
			builder.setTitle("Warning")
					.setIcon(android.R.drawable.ic_dialog_alert)
					.setMessage(message)
					.setPositiveButton("Ja", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							sendLogs(dialog);
						}
					}).setNegativeButton("Nein", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			dialog = builder.create();
			break;
		case DIALOG_PROGRESS_COLLECTING_LOG:
			ProgressDialog pd = new ProgressDialog(this);
			pd.setTitle("in Arbeit");
			pd.setMessage("Sammle Logs...");
			pd.setIndeterminate(true);
			dialog = pd;
			break;
		case DIALOG_FAILED_TO_COLLECT_LOGS:
			builder = new AlertDialog.Builder(this);
			builder.setTitle("Error").setMessage("Failed to collect logs.")
					.setNegativeButton("OK", null);
			dialog = builder.create();
		}
		return dialog;
	}

	/**
	 * Asynchroner Task, der die Logs nach Fehlermeldungen durchsucht.
	 * 
	 * @author watho
	 * 
	 */
	class CheckForceCloseTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected Boolean doInBackground(Void... params) {
			return logCollector.hasForceCloseHappened();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				showDialog(DIALOG_REPORT_FORCE_CLOSE);
			}
		}
	}

	public void sendLogs(DialogInterface dialog) {
		new AsyncTask<Void, Void, Boolean>() {
			@Override
			protected Boolean doInBackground(Void... params) {
				logPrefs();
				return logCollector.collect();
			}

			@Override
			protected void onPreExecute() {
				showDialog(DIALOG_PROGRESS_COLLECTING_LOG);
			}

			@Override
			protected void onPostExecute(Boolean result) {
				dismissDialog(DIALOG_PROGRESS_COLLECTING_LOG);
				if (result)
					logCollector.sendLog("wathosoft@gmx.net", "Error Log",
							"Preface\nPreface line 2");
				else
					showDialog(DIALOG_FAILED_TO_COLLECT_LOGS);
			}
		}.execute();
		dialog.dismiss();
	}
}
